package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net"
	"net/http"
	"regexp"

	"github.com/gorilla/mux"
	"github.com/malfunkt/hyperfox/lib/plugins/capture"
)

var (
	cleanPattern  = regexp.MustCompile(`[^0-9a-zA-Z\s\.]`)
	spacesPattern = regexp.MustCompile(`\s+`)
)

const (
	serviceBindHost      = `127.0.0.1`
	serviceBindStartPort = 3030
)

const (
	pageSize         = 50
	directionRequest = `req`
)

type getResponse struct {
	capture.Response `json:",inline"`
}

type pullResponse struct {
	Data  []capture.Response `json:"data"`
	Pages uint               `json:"pages"`
	Page  uint               `json:"page"`
}

func replyCode(w http.ResponseWriter, httpCode int) {
	w.WriteHeader(httpCode)
	w.Write([]byte(http.StatusText(httpCode)))
}

func replyJSON(w http.ResponseWriter, data interface{}) {
	var buf []byte
	var err error

	if buf, err = json.Marshal(data); err != nil {
		log.Printf("Marshal: %q", err)
		replyCode(w, http.StatusInternalServerError)
		return
	}

	w.Header().Set("Access-Control-Allow-Origin", "*")

	w.WriteHeader(http.StatusOK)
	w.Write(buf)
}

func rootHandler(http.ResponseWriter, *http.Request) {

}

// startServices starts an http server that provides websocket and rest
// services.
func startServices() error {

	r := mux.NewRouter()

	r.HandleFunc("/", rootHandler)

	log.Printf("Starting (local) API server...")

	// Looking for a port to listen to.
	ln, err := net.Listen("tcp", serviceBindHost+":0")
	if err != nil {
		log.Fatal("net.Listen: ", err)
	}

	addr := fmt.Sprintf("%s:%d", serviceBindHost, ln.Addr().(*net.TCPAddr).Port)
	log.Printf("Watch live capture at http://live.hyperfox.org/#/?source=%s", addr)

	srv := &http.Server{
		Addr:    addr,
		Handler: r,
	}

	// Serving API.
	go func() {
		if err := srv.Serve(ln); err != nil {
			panic(err.Error())
		}
	}()

	return err
}
